package com.dapeis.api.utils.threadlocal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ag.utils.NumberUtils;
import com.ag.utils.SpringUtils;
import com.dapeis.domain.Collocation;
import com.dapeis.service.CollocationService;

public class CollocationThreadLocal extends ThreadLocal<Collocation> {
    public final Logger logger = LoggerFactory.getLogger(getClass());
    ThreadLocal<Integer> collocationIdThreadLocal = new ThreadLocal<Integer>();

    public CollocationThreadLocal() {
    }

    public CollocationThreadLocal(Integer partnerId) {
    }

    @Override
    public Collocation get() {
	Thread t = Thread.currentThread();
	logger.debug("getThreadLocalPartner.get:" + t);
	Collocation collocation = super.get();
	if (collocation == null) {
	    logger.warn("collocation is null.");
	}
	return collocation;
    }

    @Override
    protected Collocation initialValue() {
	Integer collocationId = collocationIdThreadLocal.get();
	if (NumberUtils.isNotValid(collocationId)) {
	    return null;
	}

	CollocationService collocationService = SpringUtils
		.getBean(CollocationService.class);
	Collocation collocation = collocationService
		.getCollocation(collocationId);
	if (collocation == null) {
	    logger.warn("不存在的搭配师:" + collocationIdThreadLocal);
	}
	return collocation;
    }

    @Override
    public void remove() {
	Thread t = Thread.currentThread();
	logger.debug("getThreadLocalPartner.remove:" + t);
	super.remove();
	this.collocationIdThreadLocal.remove();
    }

    public void resetCollocationId(Integer collocationId) {
	this.remove();
	this.collocationIdThreadLocal.set(collocationId);
    }
}